package org.csu.myblogger.myblogger.commom;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil {
    // 使用固定密钥（至少 256 位/32 字节）
    private static final String SECRET = "YourFixedSecretKeyAtLeast32BytesLong!";
    private static final Key SHARK = new SecretKeySpec(SECRET.getBytes(), SignatureAlgorithm.HS256.getJcaName());

    public static String generateToken(String username) {
        long nowMillis = System.currentTimeMillis();
        long expirationMillis = nowMillis + 3600 * 1000; // 1 小时

        Date now = new Date(nowMillis);
        Date expiration = new Date(expirationMillis);

        Map<String, String> map = new HashMap<>();
        map.put("username", username);
        ObjectMapper objectMapper = new ObjectMapper();
        String subject;
        try {
            subject = objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        return Jwts.builder()
                .setHeaderParam("type", "Jwt")
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(SHARK)
                .compact();
    }

    public static Claims getClaimsByToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(SHARK)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    public String getUsernameFromToken(String token) throws JsonProcessingException {
        String subject = Jwts.parserBuilder()
                .setSigningKey(SHARK)
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();

        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> subjectMap = objectMapper.readValue(subject, new TypeReference<Map<String, String>>() {});
        return subjectMap.get("username");
    }
}
